home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6322 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: columba.udac.uu.se!news
  2. From: Enrico Savazzi <enrico.savazzi@pal.uu.se>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: new and 2-D Arrays?
  5. Date: Thu, 08 Feb 1996 16:55:37 +0100
  6. Organization: Uppsala University
  7. Message-ID: <311A1CF9.5D84@pal.uu.se>
  8. References: <4famh5$chp@canyon.sr.hp.com> <4fatc0$8lg@cloner4.netcom.com>
  9. NNTP-Posting-Host: esavazzi.pal.uu.se
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (WinNT; I)
  14.  
  15. Michael Judge wrote:
  16. > In <4famh5$chp@canyon.sr.hp.com> rolando@sr.hp.com (Rolando Ampuero)
  17. > writes:
  18. > >
  19. > >Hello, This question was problably asked already, but as a newbie in
  20. > the
  21. > >world of C++, this is one place I found that relates to this subject.
  22. > >According to several manuals that I have read I can declare a two
  23. > dimensional
  24. > >array in this manner
  25. > >
  26. > >int *myptr = new int [8][8];
  27. > >
  28. > >but when I tried to compile I get errors, is this not the correct way
  29. > to do
  30. > >it? Are the books wrong? (One of the books is Deitel pg 415).I passed through the same stage, and found an answer by accident only much later. 
  31. I do not know of any compiler that will accept your solution. If you know the size 
  32. of the array at compile time, then declare it statically:
  33. int a[8][8];
  34.  
  35. otherwise, use new. However, keep in mind that a two-dimensional array requires a 
  36. pointer to an array of pointers to arrays. Therefore:
  37. int** a; // not just int*
  38. a = new int* [m];
  39. for (int i = 0; i < m; i++)
  40.     a[i] = new int [n];
  41. // use the array a[m][n] here
  42. for (i = 0; i < m; i++)
  43.     delete [] a[i];
  44. delete a;
  45.  
  46. Note that you must delete in reverse order, or the code will bomb. If you need 
  47. three or more dimensions, nest more loops. Keep in mind, however, that 
  48. uni-dimensional arrays are faster to access than multi-dimensional ones. If you 
  49. want speed, use a uni-dimensional array and do the pointer arithmetics explicitly. 
  50. Another big difference between uni- and multi-dimensional arrays is that uni's are 
  51. contiguous in memory, while multi's need not to be. Multi's also require more 
  52. memory to store the arrays of pointers.
  53.